
import webview
from api.difyApi import AiApi
from api.yuYinApi import SpeakToText
from api.sshApi import SSHConnectionPool
import json
from operator import methodcaller
import time
from api.backend import init_config_manager
from backend.session_manager import init_session_manager
from backend.terminal_manager import init_terminal_manager
from api.model_handlers import BlPtHandler, DiffOllamaDkr1Handler ,OllamaDkr1Handler,KouZiHanler
position ={
    "cx": 0,
    "cy": 0
}
class Tool:
    aiApi = None;
    speakToText = None;
    pool = None;
    tools = {};
    config_manager = None;
    session_manager = None;
    terminal_manager = None;

tool = Tool();

def loadFile(vueFile):
    print(vueFile)
    content = ""
    try:
        with open("./www/"+vueFile, 'r', encoding='gbk', errors='ignore') as file:
            content = file.read()
    except FileNotFoundError:
        print("文件不存在！")
    return content

def initTools():
    #获取有哪些工具及工具方法的参数
    return [
      {
        'type': 'function',
        'function': {
          'name': 'get_connection',
          'description': '连接hostname服务器,未连接的情况下使用',
          'input_schema': {
            'properties': {
              'hostname': {
                'title': 'Hostname',
                'type': 'string'
              },'port': {
                'title': 'Port',
                'type': 'integer'
              },'username': {
                'title': 'UserName',
                'type': 'string'
              },'password': {
                'title': 'Password',
                'type': 'string'
              }
            },
            'required': [
              'hostname',
              'port',
              'username',
              'password'
            ],
            'title': 'connectArguments',
            'type': 'object'
          }
        }
      },
    {
        'type': 'function',
        'function': {
            'name': 'send_command',
            'description': '使用已有会话执行shell命名',
            'input_schema': {
                'properties': {
                    'hostname': {
                        'title': 'Hostname',
                        'type': 'string'
                    },
                    'command': {
                        'title': 'command',
                        'type': 'string'
                    }
                },
                'required': [
                    'hostname',
                    'command'
                ],
                'title': 'execArguments',
                'type': 'object'
            }
        }
    }
    ]

def sendMsg(query):
    print("sendMsg:"+query)
    window.evaluate_js("startReponse()")
    #获取当前的模型
    current_model = tool.config_manager.get_model_config(tool.config_manager.current_model)
    handler_class_name = tool.config_manager.get_model_handler_name(current_model['value'])
    if not handler_class_name:
        window.evaluate_js(f"updateMsg('不支持该模型: {current_model['value']}')")
        return
    try:
        # 动态创建处理器实例
        handler_class = globals()[handler_class_name]
        handler = handler_class(window)
        response = handler.handle(query, current_model)
        # window.evaluate_js(f"updateMsg('{response}')")
    except Exception as e:
        errmsg = f"处理请求时出错: {str(e)}"
        print(errmsg)
        window.evaluate_js("updateMsg(\""+errmsg+"\")")
    # time.sleep(5)
    # window.evaluate_js("updateMsg(\"" + query + "\")")

def sendMsg2(query):
    inputs = {
            "query": query,
            "tools": str(tool.tools)
    }
    tool.aiApi.headers["Authorization"]="Bearer app-H42wbbXFI5qrE9IJs75zIHaA";
    allResponse = tool.aiApi.sendMsg_(inputs);
    response_ = allResponse.replace('\\n', '').replace('\\"', '\"')
    try:
        response_ = json.loads(response_)
        toolCalls = response_["tool_calls"]
        desc = response_["desc"]
        window.evaluate_js("okMsg(\"" + desc + "\")")
        for toolCall in toolCalls:
            tCall = toolCall["tool_call"]
            tName = tCall["tool_name"]
            tArgs = tCall["tool_args"]
            print("start methodcaller" + str(tName))
            caller = methodcaller(tName, **tArgs)
            result = caller(tool.pool)
            print("result"+str(result))
    except Exception as e:
        print("---{}",e)
    print("allResponse:"+str(response_))


def startSpeakToText():
    print("startSpeakToText")
    try:
        tool.speakToText.start()
    except Exception as e:
        print(f"Caught exception: {e}")

def stopSpeakToText():
    print("stopSpeakToText")
    try:
        tool.speakToText.stop()
    except Exception as e:
        print(f"Caught exception: {e}")


def startDrag():
    print("开始拖动")
def mvWindow(deltaX, deltaY):
    position["cx"] = position["cx"] + deltaX;
    position["cy"] = position["cy"] + deltaY;
    window.move(position["cx"], position["cy"])

windowAttr={
    "width":1200,
    "height": 800
}

def initBefore(window):
    tool.tools = initTools();
    tool.speakToText = SpeakToText(window);
    tool.aiApi = AiApi(window);
    tool.pool = SSHConnectionPool(pool_size=5, idle_timeout=30,window=window)
    tool.config_manager = init_config_manager(window)
    tool.session_manager = init_session_manager(window)
    tool.terminal_manager = init_terminal_manager(window)

    window.expose(sendMsg)
    window.expose(startSpeakToText)
    window.expose(stopSpeakToText)
    window.expose(loadFile)
    window.expose(startDrag)
    window.expose(mvWindow)
    window.expose(close_window)
    window.expose(minimize_window)
    window.expose(toggle_fullscreen)
    def get_window_position():
        x, y = 200,100;
        window.move(x,y)
        position["cx"] = x;
        position["cy"] = y;
    get_window_position()

def close_window():
    window.destroy()
def minimize_window():
    window.minimize()
def toggle_fullscreen():
    window.toggle_fullscreen()

if __name__ == '__main__':
    icon_path="www/image/logo.png"
    window = webview.create_window('智能体运维-webview', 'www/index.html', background_color="#000000",frameless=True,easy_drag=False,
                          width=windowAttr["width"], height=windowAttr["height"])

    webview.start(initBefore, window, debug=False)


